home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6766 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: cafu.fl.net.au!usenet
  2. From: als@fl.net.au (Andrew Snow)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to tell if a file exists in C
  5. Date: Thu, 15 Feb 1996 00:02:14 GMT
  6. Organization: First Link Internet Services
  7. Message-ID: <4ftpnk$i74@cafu.fl.net.au>
  8. References: <4eqkj6$ipo@charm.magnus.acs.ohio-state.edu> <4eqn9q$dr1@sparcserver.lrz-muenchen.de> <3121db3e.43150046@nntp.ix.netcom.com>
  9. NNTP-Posting-Host: snowville.fl.net.au
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. miker3@ix.netcom.com (Mike Rubenstein) wrote:
  13.  
  14. >ua302aa@sun2.lrz-muenchen.de (Kurt Watzka) wrote:
  15.  
  16. >> xiaoyi@bmecg.bme.ohio-state.edu (Xiaoyi Wu) writes:
  17. >> 
  18. >> >Hi, how do I find out if a file already exists
  19. >> >in UNIX C? On PCs I would do a findfirst/findnext,
  20. >> >is there an equivalent on Unix?
  21. >> 
  22. >> Yes, there is an equivalent in a POSIX environment, but there 
  23. >> is a portable solution in C, too. The fopen()-function can 
  24. >> be used to decide whether a file is accessible for reading,
  25. >> and if it is not accessible for reading, errno can be used
  26. >> to detect the reason for that.
  27.  
  28. >Unfortunately, this is not portable.  Nothing in the C standard
  29. >requires fopen() to set errno to a sensible value (or, for that
  30. >matter, to set it at all) if there is an error.
  31.  
  32. How about plain old:
  33.  
  34.     if(0==access("filename", F_OK))
  35.         {
  36.         do stuff with file();
  37.         }
  38.     else
  39.         {
  40.         error();
  41.         }
  42.  
  43. This works O.K. under Linux and FreeBSD, and most DOS compilers.
  44.  
  45. If you want to see if the file is readable as well as exists,
  46. use     if(0==access("filename", F_OK | R_OK))
  47.         ...
  48.  
  49. or writeable, use F_OK | R_OK | W_OK
  50.  
  51.  
  52. and so on.
  53.  
  54.  
  55. ----
  56. Andrew Snow
  57. als@fl.net.au
  58.  
  59.